import {
	constantRoutes,
	asyncRoutesComponents
} from '@/router'
import Layout from '@/layout'
import { isArray } from '@/utils/util.js'

function checkHasRight(name, right){
	let flag = false
	if(right.name && right.name == name){
		flag = true
	}else {
		if(right.children && isArray(right.children) && right.children.length>0){
			for(let i in right.children){
				flag = (flag || checkHasRight(name, right.children[i]))
			}
		}else{
			flag = false
		}
	}
	return flag
}

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
	if (route.meta && route.meta.roles) {
		return roles.some(role => route.meta.roles.includes(role))
	} else {
		return true
	}
}

function hasDynamicPermission(rights, route) {
	if (route.name) {
		return rights.some(right => '' + right.name == '' + route.name)
	} else {
		return false;
	}

}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes rights
 * @param roles
 */
export function filterAsyncRoutes(routes) {
	const res = []

	routes.forEach(route => {
		const tmp = { ...route
		}
		if (tmp.children) {
			tmp.children = filterAsyncRoutes(tmp.children)
		}
		tmp.component = asyncRoutesComponents[tmp.component]
		if(tmp.name === 'work_order_contract_export_page') tmp.meta.navNotShow=true
		res.push(tmp)
	});
	return res
}

const state = {
	routes: [],
	addRoutes: []
}

const mutations = {
	SET_ROUTES: (state, routes) => {
		state.addRoutes = routes
		state.routes = constantRoutes.concat(routes)
	}
}

const actions = {
	generateRoutes({
		commit
	}, rights) {
		return new Promise(resolve => {
			let accessedRoutes;
			accessedRoutes = [
				...filterAsyncRoutes(rights),
				{
					path: '/',
					redirect: '/login',
					hidden: true
				},
				{
					path: '*',
					redirect: '/404',
					hidden: true
				}
			];
			console.log("accessedRoutes---------",accessedRoutes);
			commit('SET_ROUTES', accessedRoutes)
			resolve(accessedRoutes)
		})
	},
	checkRight({
		commit
	}, info){
		const {name, rights} = info
		return new Promise(resolve => {
			let hasRight = false
			for(let i in rights){
				hasRight = hasRight || checkHasRight(name,rights[i])
			}
			resolve(hasRight)
		})
	},
	checkRights({
		commit
	}, info){
		const {names, rights} = info
		return new Promise(resolve => {
			let results = []
			for(let k in names){
				let hasRight = false
				for(let i in rights){
					hasRight = hasRight || checkHasRight(names[k],rights[i])
				}
				results.push(hasRight)
			}
			resolve(results)
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
